<template>
  <div class="app-container">
    <div>
      <el-form
        :inline="true"
        size="mini"
        @keyup.enter.native="getDataList()"
      >
        <el-form-item>
          <el-input
            v-model="pageParam.queryParam"
            maxlength="30"
            placeholder="用户名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="getDataList()"
          >
            搜索
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="openAdd()"
          >
            新增
          </el-button>
          <el-button
            :disabled="dataListSelections.length <= 0"
            type="danger"
            icon="el-icon-delete"
            @click="batchDelete()"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
      <el-tooltip :content="'Switch value: '" placement="top" />
    </div>
    <div>
      <el-table
        v-loading="dataListLoading"
        :data="dataList"
        border
        resizable
        stripe
        size="mini"
        highlight-current-row
        style="width: 100%;height:100%"
        @selection-change="selectionChangeHandle"
      >
        <el-table-column
          type="selection"
          width="40"
        />
        <el-table-column
          prop="userNo"
          show-overflow-tooltip
          label="用户账号"
        />
        <el-table-column
          prop="userName"
          show-overflow-tooltip
          label="用户名称"
        />
        <el-table-column
          prop="deptName"
          wshow-overflow-tooltip
          label="所属机构"
        />
        <el-table-column
          prop="email"
          show-overflow-tooltip
          label="邮箱"
        />
        <el-table-column
          prop="mobile"
          show-overflow-tooltip
          label="手机号"
        />
        <el-table-column
          prop="status"
          width="80"
          label="状态"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status===0">
              正常
            </el-tag>
            <el-tag v-else-if="scope.row.status===1" type="danger">
              禁用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          show-overflow-tooltip
          label="备注信息"
        />
        <el-table-column
          prop="createUserNo"
          show-overflow-tooltip
          label="创建用户"
        />
        <el-table-column
          prop="createTime"
          show-overflow-tooltip
          label="创建时间"
        />
        <el-table-column
          prop="updateUserNo"
          show-overflow-tooltip
          label="修改用户"
        />
        <el-table-column
          prop="updateTime"
          show-overflow-tooltip
          label="修改时间"
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              content="修改"
              placement="top"
            >
              <el-button
                type="primary"
                circle
                size="mini"
                icon="el-icon-edit"
                @click="openUpdate(scope.row.userId)"
              />
            </el-tooltip>
            <el-tooltip
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                circle
                size="mini"
                icon="el-icon-delete"
                @click="deleteUser(scope.row.userId,scope.row.userNo)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        style="float:right;margin-top:5px;"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <!-- 新增修改用户 -->
    <el-dialog :visible.sync="formVisible" :title="title" width="38%" @close="resetUserForm()">
      <el-form ref="userForm" :model="userForm" :rules="userFromRules" :inline="true" class="demo-ruleForm" prop="userNo" size="mini">
        <el-form-item
          :label-width="formLabelWidth"
          :rules="[
            { required: true, message: '请输入用户名',trigger: 'change'},
          ]"
          label="用户账号"
          required
          prop="userNo"
        >
          <el-input v-model="userForm.userNo" :disabled="userNoDisabled" placeholder="请输入用户名（6-12位）" autocomplete="off" />
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          :rules="[
            { required: true, message: '请填写用户名称',trigger: 'blur'},
          ]"
          label="用户名称"
          prop="userName"
        >
          <el-input v-model="userForm.userName" placeholder="请输入用户名称（6-12位）" autocomplete="off" />
        </el-form-item>
        <el-form-item
          :rules="[
            { required: true, message: '请选择用户所属的部门',trigger: 'change'},
          ]"
          :label-width="formLabelWidth"
          prop="deptCode"
          label="所属机构"
        >
          <el-cascader
            v-model="userForm.deptCode"
            :options="deptInfoTreeData"
            placeholder="选择所属机构"
            filterable
            style="width:170px"
            @change="deptChange"
          />
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          :rules="[
            { required: true, message: '请输入用户的初始密码',trigger: 'blur'},
            { min: 8, max: 16, message: '长度在8到16个字符', trigger: 'blur'}
          ]"
          prop="password"
          label="密码"
        >
          <el-input v-model="userForm.password" :disabled="pwdDisabled" placeholder="请输入初始密码（8-16位）" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item
          :rules="[
            { type:'email', message: '请输入正确的邮箱地址',trigger: ['blur'] }
          ]"
          :label-width="formLabelWidth"
          prop="email"
          label="邮箱"
        >
          <el-input v-model="userForm.email" placeholder="请输入邮箱地址" autocomplete="off" />
        </el-form-item>
        <el-form-item
          :rules="[
            {max: 11, message: '手机号码应为11位',trigger: ['blur'] }
          ]"
          :label-width="formLabelWidth"
          prop="mobile"
          label="手机号码"
        >
          <el-input v-model="userForm.mobile" placeholder="请输入手机号码" autocomplete="off" />
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          :rules="[
            { max: 20, message: '长度须在20个字符以内', trigger: 'blur'}
          ]"
          prop="remark"
          label="备注"
        >
          <el-input v-model="userForm.remark" placeholder="用户备注信息" autocomplete="off" />
        </el-form-item>
        <el-form-item
          :rules="[
            { type:'array', required: true, message: '请至少选择一个用户角色',trigger: 'blur'}
          ]"
          :label-width="formLabelWidth"
          prop="roleIds"
          label="用户角色"
        >
          <el-select
            v-model="userForm.roleIds"
            multiple
            collapse-tags
            style="width:170px"
            placeholder="请选择用户角色"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="状态">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="0">
              正常
            </el-radio>
            <el-radio :label="1">
              禁用
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span style="padding-left:35%" class="dialog-footer">
        <el-button :loading="submitLoad" size="mini" type="primary" @click="submitUserData()">确 定</el-button>
        <el-button size="mini" @click="formVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 用户名验证规则
    var validateUserNo = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      }
      if (value.length < 5 || value.length > 12) {
        callback(new Error('用户名长度应为6-12位！'))
      }
      setTimeout(() => {
        this.httpRequest({
          url: '/sys/user/verifyUserNo/' + value,
          responseType: 'json',
          method: 'get'
        }).then(response => {
          if (!response.body) {
            callback(new Error('用户名已经被使用！'))
          }
        })
      }, 1000)
    }
    return {
      aaa: 1,
      pageParam: {

      },
      pwdDisabled: false,
      userNoDisabled: false,
      oldUserData: null,
      queryParam: '',
      userFromRules: {
        userNo: [{ validator: validateUserNo, trigger: 'blur' }]
      },
      title: '新增用户',
      options: [],
      deptInfoTreeData: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      formVisible: false,
      submitLoad: false,
      dataListLoading: false,
      userForm: {
        userId: '',
        userNo: '',
        userName: '',
        deptCode: null,
        password: '',
        email: '',
        mobile: '',
        remark: '',
        status: 1,
        roleIds: []
      },
      formLabelWidth: '80px',
      dataListSelections: [],
      addOrUpdateVisible: false
    }
  },
  created() {
    this.getDataList()
  },
  activated() {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList() {
      const that = this
      that.dataListLoading = true
      this.httpRequest({
        url: '/sys/user/list',
        method: 'post',
        data: {
          pageNumber: this.pageIndex,
          pageSize: this.pageSize,
          queryParam: this.queryParam
        }
      }).then(response => {
        if (response.code === 0) {
          that.dataList = response.body.records
          that.totalPage = response.body.total
        }
        that.dataListLoading = false
      }).catch(() => {
        that.dataListLoading = false
      })
    },

    // 批量删除用户
    batchDelete() {
      const that = this
      var deleteUserIds = []
      that.dataListSelections.forEach(item => {
        deleteUserIds.push(item.userId)
      })
      console.log(deleteUserIds)
      this.$confirm('此操作将选中的用户删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.httpRequest({
          url: '/sys/user/delete',
          responseType: 'json',
          method: 'post',
          data: { userIds: deleteUserIds }
        }).then(response => {
          that.getDataList()
          that.$message({
            showClose: true,
            message: '删除成功！',
            type: 'success'
          })
        })
      })
    },

    // 删除用户
    deleteUser(userId, userNo) {
      const that = this
      const deleteUserIds = [userId]
      this.$confirm('此操作将用户' + userNo + '删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.httpRequest({
          url: '/sys/user/delete',
          responseType: 'json',
          method: 'post',
          data: { userIds: deleteUserIds }
        }).then(response => {
          that.getDataList()
          that.$message({
            showClose: true,
            message: '用户' + userNo + '成功被删除！',
            type: 'success'
          })
        })
      })
    },
    // 修改用户状态
    updateStaus(userId, userNo, status) {
      console.log('userId:' + userId + ',status:' + status)
      const that = this
      let url = '/sys/user/disable/' + userId
      let msg = '用户' + userNo + '成功被禁用！'
      if (status === 1) {
        url = '/sys/user/enable/' + userId
        msg = '用户' + userNo + '成功被启用！'
      }
      this.httpRequest({
        url: url,
        responseType: 'json',
        method: 'put'
      }).then(response => {
        that.$message({
          showClose: true,
          message: msg,
          type: 'success'
        })
      })
    },

    // 获取选择的部门名称
    deptChange() {
      var code = this.userForm.deptCode
      var opt = this.deptInfoTreeData
      var label = ''
      for (var item of code) {
        for (var i of opt) {
          if (i.value == item) {
            opt = i.children
            label = i.label
            break
          }
        }
      }
      console.log(label)
      this.userForm.deptName = label
    },

    // 修改用户资料
    updatedUser() {
      const that = this
      this.$refs['userForm'].validateField(
        ['mobile', 'email'],
        errorMessage => {
          console.log(
            '校验结果：' + (errorMessage != null && errorMessage !== '')
          )
          if (errorMessage != null && errorMessage !== '') {
            console.log(errorMessage)
            return
          } else {
            that.submitLoad = true
            this.httpRequest({
              url: '/sys/user/update',
              responseType: 'json',
              method: 'put',
              data: this.userForm
            })
              .then(response => {
                that.getDataList()
                that.submitLoad = false
                that.formVisible = false
                this.resetForm('userForm')
                that.$message({
                  showClose: true,
                  message: '用户' + that.userForm.userNo + '的信息修改成功！',
                  type: 'success'
                })
              })
              .catch(function() {
                that.submitLoad = false
              })
          }
        }
      )
    },
    // 验证用户名是否唯一
    verifyUserNo(userNo) {
      this.httpRequest({
        url: '/sys/user/verifyUserNo/' + userNo,
        responseType: 'json',
        method: 'get'
      }).then(response => {
        if (response.body) {
          return true
        }
        return false
      })
    },

    // 根据用户id获取用户信息
    getUserInfo(userId) {
      const that = this
      this.httpRequest({
        url: '/sys/user/info/' + userId,
        responseType: 'json',
        method: 'get'
      }).then(response => {
        that.userForm = response.body
        that.oldUserData = JSON.stringify(that.userForm)
        console.log(that.userForm)
      })
    },

    // 打开用户修改窗口
    openUpdate(userId) {
      this.initData('修改用户')
      this.getUserInfo(userId)
      // 禁用密码修改
      this.pwdDisabled = true
      //
      this.userNoDisabled = true
    },
    // 打开用户新增窗口
    openAdd() {
      this.oldUserData = JSON.stringify(this.userForm)
      this.initData('新增用户')
      // 不禁用密码修改
      this.pwdDisabled = false
      // 不禁用用户名
      this.userNoDisabled = false
    },
    // 添加用户窗口需要初始化操作
    initData(title) {
      this.title = title
      // 打开新增窗口
      this.formVisible = true
      this.getAllDept()
      this.getAllRole()
      // 初始化对象数据
      this.userForm = {
        userId: '',
        userNo: '',
        userName: '',
        deptCode: null,
        deptName: '',
        password: '',
        email: '',
        mobile: '',
        remark: '',
        status: 1,
        roleIds: []
      }
    },

    // 获取部门信息
    getAllDept() {
      const that = this
      this.httpRequest({
        url: '/sys/dept/list/frontShow',
        responseType: 'json',
        method: 'get'
      }).then(function(response) {
        console.log(response.body)
        that.deptInfoTreeData = response.body
      })
    },
    // 获取角色信息
    getAllRole() {
      const that = this
      this.httpRequest({
        url: '/sys/role/list/frontShow',
        responseType: 'json',
        method: 'get'
      }).then(function(response) {
        that.options = response.body
      })
    },

    // 提交用户表单数据
    submitUserData() {
      if (JSON.stringify(this.userForm) === this.oldUserData) {
        this.formVisible = false
        return
      }
      // 根据是否有用户ID来判断是新增还是修改用户数据
      console.log(this.userForm.userId)
      if (this.userForm.userId) {
        console.log('修改用户')
        this.updatedUser()
      } else {
        console.log('新增用户')
        this.addUser()
      }
    },
    // 新增用户
    addUser() {
      const that = this
      this.submitLoad = true
      this.httpRequest({
        url: '/sys/user/add',
        responseType: 'json',
        method: 'post',
        data: this.userForm
      })
        .then(function(response) {
          that.submitLoad = false
          that.getDataList()
          that.formVisible = false
          this.resetForm('userForm')
          that.$message({
            showClose: true,
            message: '新增用户成功！',
            type: 'success'
          })
        })
        .catch(function() {
          that.submitLoad = false
        })
    },
    // 清除新增表单数据
    resetUserForm() {
      console.log(JSON.stringify(this.userForm))
      console.log(this.oldUserData)
      if (JSON.stringify(this.userForm) !== this.oldUserData) {
        this.$confirm('用户数据有变更, 是否保存?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitUserData()
        })
      } else {
        this.formVisible = false
        this.resetForm('userForm')
      }
    },

    // 清除表单数据
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.userForm = {
        userId: '',
        userNo: '',
        userName: '',
        deptCode: null,
        password: '',
        email: '',
        mobile: '',
        remark: '',
        status: 1,
        roleIds: []
      }
      this.oldUserData == null
    },

    // 每页数
    sizeChangeHandle(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      console.log(`当前页: ${val}`)
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    }
  }
}
</script>
